package com.huyi.thread;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程等待 - Wait 释放锁
 * 线程通知 - notify  不释放锁
 * Wait和notify必须配合synchronized使用，但是notify不释放锁，所以t1程序中只有等t2执行完才能得到锁，即不是实时的
 * 
 * @author shengli.hu
 *
 */
public class WaitNotifyDemo {

	public static void main(String[] args) throws InterruptedException {
		
		AtomicInteger count = new AtomicInteger(0);
		
		Object lock = new Object();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				synchronized (lock) {
					System.out.println(Thread.currentThread() + "启动开始");
					if(count.get() < 5) {
						try {
							lock.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					System.out.println(Thread.currentThread() + "收到通知，暂停操作。。");
					try {
						throw new InterruptedException(Thread.currentThread() + "xxx");
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}

			}
		}, "t1").start();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				synchronized (lock) {
					for(int i=0;i<10;i++) {
						count.incrementAndGet();
						System.out.println(Thread.currentThread() + "计数器count = " +count);
						if(count.get() == 5) {
							lock.notify();
							System.out.println(Thread.currentThread() + "通知唤醒操作。。。");
						}
					}

				}
			}
		}, "t2").start();
	}
}


